package com.cloudsea.yunhaianalysis.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.lang.Snowflake;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cloudsea.yunhaianalysis.dto.EventAddDTO;
import com.cloudsea.yunhaianalysis.entity.Events;
import com.cloudsea.yunhaianalysis.mapper.EventsMapper;
import com.cloudsea.yunhaianalysis.service.EventService;
import com.cloudsea.yunhaistores.entity.MerchantUsers;
import com.cloudsea.yunhaistores.entity.Stores;
import com.cloudsea.yunhaistores.mapper.MerchantUsersMapper;
import com.cloudsea.yunhaistores.mapper.StoresMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;

@Service
public class EventServiceImpl implements EventService {
    @Autowired
    private EventsMapper eventsMapper;

    @Autowired
    private Snowflake snowflake;

    @Autowired
    private MerchantUsersMapper merchantUsersMapper;

    @Autowired
    private StoresMapper storesMapper;
    @Override
    public Events addEvent(EventAddDTO dto) {
        // 在执行任何业务逻辑前，先进行权限校验
        this.checkStorePermission(dto.getStoreId());

        Events event = new Events();
        event.setId(snowflake.nextId());
        event.setStoreId(dto.getStoreId());
        event.setEventDate(dto.getEventDate());
        event.setEventType(dto.getEventType());
        event.setDescription(dto.getDescription());
        event.setCreatedBy(StpUtil.getLoginIdAsLong());
        event.setCreatedAt(LocalDateTime.now());

        eventsMapper.insert(event);
        return event;
    }

    @Override
    public List<Events> listEventsByDate(Long storeId, LocalDate date) {
        // 权限校验
        this.checkStorePermission(storeId);

        QueryWrapper<Events> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("store_id", storeId).eq("event_date", date);
        return eventsMapper.selectList(queryWrapper);
    }

    @Override
    public void deleteEvent(Long eventId) {
        // 对于删除操作，权限校验稍微复杂一些
        Events event = eventsMapper.selectById(eventId);
        if (event != null) {
            // 我们需要先查出事件，然后根据事件的storeId进行权限校验
            this.checkStorePermission(event.getStoreId());
            eventsMapper.deleteById(eventId);
        }
        // 如果 event 为 null，说明事件本不存在，无需操作也无需报错
    }

    /**
     * 【新增】权限校验私有方法
     * 检查当前登录用户是否有权操作指定的门店
     * @param storeId 门店ID
     */
    private void checkStorePermission(Long storeId) {
        if (storeId == null) {
            throw new IllegalArgumentException("门店ID不能为空");
        }

        long loginId = StpUtil.getLoginIdAsLong();
        MerchantUsers currentUser = merchantUsersMapper.selectById(loginId);
        if (currentUser == null || currentUser.getMerchantId() == null) {
            throw new SecurityException("无法获取当前用户信息，权限校验失败");
        }
        Long operatorMerchantId = currentUser.getMerchantId();

        Stores targetStore = storesMapper.selectById(storeId);
        if (targetStore == null) {
            throw new RuntimeException("操作的门店不存在");
        }
        Long targetMerchantId = targetStore.getMerchantId();

        if (!operatorMerchantId.equals(targetMerchantId)) {
            throw new SecurityException("权限不足，您只能为自己商户下的门店添加事件");
        }
    }
}
